package com.mindata.blockchain.socket.handler.server.block;

import com.mindata.blockchain.ApplicationContextProvider;
import com.mindata.blockchain.block.block.Block;
import com.mindata.blockchain.block.block.DGLBlock;
import com.mindata.blockchain.common.CommonUtil;
import com.mindata.blockchain.common.Commonvalue;
import com.mindata.blockchain.core.event.DGLAddBlocksEvent;
import com.mindata.blockchain.core.manager.DbBlockGenerator;
import com.mindata.blockchain.core.manager.DbBlockManager;
import com.mindata.blockchain.socket.base.AbstractBlockHandler;
import com.mindata.blockchain.socket.body.rpc.RpcBlockBody;
import com.mindata.blockchain.socket.body.rpc.RpcDGLBlockBody;
import com.mindata.blockchain.socket.body.rpc.RpcSimpleBlockBody;
import com.mindata.blockchain.socket.packet.BlockPacket;
import com.mindata.blockchain.socket.packet.PacketBuilder;
import com.mindata.blockchain.socket.packet.PacketType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.Aio;
import org.tio.core.ChannelContext;

import javax.swing.*;

public class DGLUpdateHandler extends AbstractBlockHandler<RpcDGLBlockBody> {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private Commonvalue commonvalue = ApplicationContextProvider.getBean(Commonvalue.class);
    private DbBlockGenerator dbBlockGenerator = ApplicationContextProvider.getBean(DbBlockGenerator.class);
    private DbBlockManager dbBlockManager = ApplicationContextProvider.getBean(DbBlockManager.class);

    @Override
    public Class<RpcDGLBlockBody> bodyClass() {
        return RpcDGLBlockBody.class;
    }

    @Override
    public Object handler(BlockPacket packet, RpcDGLBlockBody bsBody, ChannelContext channelContext) throws Exception {
        logger.info("收到来自于<{}><请求该Block>消息，block hash为[{}]", bsBody.getAppId(), bsBody.getDglBlock().getHash());
        DGLBlock dglBlock = bsBody.getDglBlock();
        if (dbBlockManager.getDGLBlockByHash(dglBlock.getHash()) == null)
            dbBlockGenerator.addDGLBlock(new DGLAddBlocksEvent(dglBlock));
        return null;
    }
}
